import React, { useState, useEffect } from "react";
import { Button, Table, Modal, message } from 'antd';
import { FormOutlined, CloseOutlined } from '@ant-design/icons';
import intl from 'react-intl-universal';
import $ from 'jquery';
import SearchBar from "./searchkBar";
import UpdateUserModal from "./updateUserModal";
import AddUserModal from "./addUserModal";
import './user.css';


// 获取角色列表
const roles = [];
const getRoles = () => {
    $.ajax({
        url: '/home/role',
        type: 'post',
        dataType: 'json',
        success: function (result) {
            if (result.status === 1) {
                // console.log('roles', result.data)    一个数组，包含多个角色对象
                result.data.map((item) => {
                    roles.push({
                        rid: item.rid,
                        roleName: item.roleName
                    });
                    return null;
                });
            }
        },
        error: function (err) {
            alert(JSON.stringify(err));
        }
    })
}
getRoles();


const User = () => {
    // 获取用户数据
    const [hasChange, setHasChange] = useState(true);
    const [userData, setUserData] = useState([]);
    useEffect(() => {
        const getUserData = () => {
            $.ajax({
                url: '/home/user',
                type: 'post',
                dataType: 'json',
                success: function (result) {
                    if (result.status === 1) {
                        // console.log('data',result.data) 数组包含用户对象，用户对象包含角色数组，角色数组包含角色对象
                        setUserData(result.data);
                    }
                },
                error: function (err) {
                    alert(err);
                }
            });
        };
        hasChange && getUserData();
        setHasChange(false);
    }, [hasChange]);


    // 角色数组
    const roleOptions = [];
    roles.map((item) => {
        roleOptions.push({
            label: item.roleName,
            value: item.rid,                // Checkbox设置的默认值对应的是value
        });
        return null;
    });


    // 增、改用户时，弹出的Modal
    const [showModal, setShowModal] = useState({
        ifShow: false,
        title: '',
        children: {}
    });
    const hideModal = () => {
        setShowModal({
            ifShow: false,
            title: '',
            children: {}
        });
    };


    // 添加用户
    const addUser = () => {
        setShowModal({
            ifShow: true,
            title: intl.get('addUser'),
            children:
                <AddUserModal roleOptions={roleOptions} setHasChange={setHasChange} hideModal={hideModal} />
        });
    };


    // 修改用户信息
    const updateUser = (val) => {
        // console.log('updated user',val)  用户对象，包含角色数组，角色数组包含角色对象
        // console.log(val.roles)           角色数组，包含角色对象
        let selectedRole = [];
        val.roles.map((item) => {
            selectedRole.push(item.rid);
            return null;
        });
        setShowModal({
            ifShow: true,
            title: intl.get('updateUser'),
            children:
                <UpdateUserModal val={val}  selectedRole={selectedRole} setHasChange={setHasChange} 
                hideModal={hideModal} roleOptions={roleOptions} />
        });
    };


    // 删除用户
    const deleteUser = (val) => {
        console.log('delete', val.uid);
        $.ajax({
            url: '/home/user/delete',
            type: 'post',
            data: { 'uid': val.uid },
            dataType: 'json',
            success: function (result) {
                if (result.status === 1) {
                    setHasChange(true);
                    message.success(intl.get('succeedToDelete'), 3);
                } else {
                    message.info(intl.get('failedToDelete'));
                }
            },
            error: function (err) {
                alert(JSON.stringify(err));
            }
        })
    }


    // 每列表头数据
    const columns = [
        {
            title: intl.get('username'),
            dataIndex: 'username',
            align: 'center',
            width: '180px',
        },
        {
            title: intl.get('name'),
            dataIndex: 'name',
            align: 'center',
            width: '180px',
        },
        {
            title: intl.get('phone'),
            dataIndex: 'phone',
            align: 'center',
            width: '130px',
        },
        {
            title: intl.get('email'),
            dataIndex: 'email',
            align: 'center',
            width: '250px',
        },
        {
            title: intl.get('gender'),
            dataIndex: 'gender',
            align: 'center',
            width: '80px',
        },
        {
            title: intl.get('description'),
            dataIndex: 'description',
            align: 'center',
            width: '320px',
        },
        {
            title: intl.get('role'),
            dataIndex: 'role',
            align: 'center',
            width: '230px',
            render: (text, record) => {                                 // 展示用户角色信息
                //console.log('record', record.roles);                  // 角色数组
                let roles = [];
                for (let i = 0; i < record.roles.length; i++) {
                    if (i !== record.roles.length - 1) {
                        roles.push(record.roles[i].roleName + ' | ');
                    } else {
                        roles.push(record.roles[i].roleName);
                    }
                }
                return (<div>{roles}</div>);
            },
        },
        {
            title: intl.get('userOperation'),
            dataIndex: 'operation',
            align: 'center',
            width: '170px',
            render: (text, record) => {                                 // 展示可执行的操作
                return (
                    <div>
                        <FormOutlined onClick={() => updateUser(record)} className='updateUser' />      {/* 修改 */}
                        <CloseOutlined onClick={() => deleteUser(record)} className='deleteUser' />          {/* 删除 */}
                    </div>
                );
            },
        }
    ];


    return (
        <div>
            <div className='userTable'>
                <div className="operationBar" style={{ marginLeft: 16 }}>
                    <SearchBar choose={roleOptions} callback={setUserData} />
                    <Button onClick={addUser} type="primary" style={{ width: '78px' }} className='addUserBtn'>{intl.get("addUser")}</Button>     {/* 添加 */}
                </div>
                <Table columns={columns} dataSource={userData} rowKey={(record) => record.uid} />       {/* 加上rowKey防止报错 */}
            </div>
            <Modal destroyOnClose='true' title={showModal.title} visible={showModal.ifShow}
                onOk={hideModal} onCancel={hideModal} okText={intl.get('yes')} cancelText={intl.get('no')}>
                {showModal.children}
            </Modal>
        </div>
    );
};

export default User;